package com.hyfrogx.modules.information.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.form.ClientInformationVo;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.information.dao.HyInformationDao;
import com.hyfrogx.modules.information.dao.InfoImgDao;
import com.hyfrogx.modules.information.entity.*;
import com.hyfrogx.modules.information.service.*;
import com.hyfrogx.modules.sys.entity.SysUserEntity;
import com.hyfrogx.modules.sys.service.SysUserRoleService;
import com.hyfrogx.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liubin
 * @date 2019/10/29 13:27
 */
@Slf4j
@Service("InformationService")
public class InformationServiceImpl extends ServiceImpl<HyInformationDao, HyInformationEntity> implements InformationService {
  @Autowired
  private HyInformationVerifyService informationVerifyService;
  @Autowired
  private UserService userService;
  @Autowired
  private SysUserRoleService userRoleService;
  @Autowired
  private InfoImgService infoImgService;
  @Autowired
  private InfoSourceServie infoSourceServie;
  @Autowired
  private InfoCommentService infoCommentService;
  @Autowired
  private InfoImgDao infoImgDao;
  @Autowired
  private InfoLikeService infoLikesService;
  @Autowired
  private SysUserService sysUserService;


  @Override
  public Page RandomGetInformationByContentType(QueryExt query) {
    Map map = new HashMap(16);
    map.putAll(query.getCondition());
    List<ClientInformationVo> list = this.baseMapper.RandomGetInformationByContentType(query, map);

    for (ClientInformationVo information : list) {
      //查询用户的头像，uid,名称，角色id
      User user = userService.getBaseMapper()
        .selectOne(new QueryWrapper<User>()
          .eq("account", information.getPublisher())
          .select("uid", "username", "head"));
      //查询用户角色
      Integer roleId = userRoleService.selectByAppUid(user.getUid().intValue());
        // 查询出来用户权限
        if (roleId== FrogConstant.Role.MEDIA) {
          // 资讯号是否子公司资讯号
          HyInformationVerifyEntity v = informationVerifyService.getAccountByUid(user.getUid());
          if (ObjectUtil.isNotNull(v)) {
            // 如果是资讯号,获取认证的用户名称和简介
            information.setUsername(v.getUserName());
            information.setSignature(v.getAuthenticationInformation());
          } else {
            information.setUsername(user.getUsername());
            information.setSignature(user.getSignature());
          }
        }

      List<InfoImgEntity> imgList = infoImgService.getBaseMapper()
        .selectList(new QueryWrapper<InfoImgEntity>()
          .eq("info_id", information.getId()));
      if (information.getAttention() != null) {
        information.setAttentions((information.getAttention()) + information.getQqClick() + information.getWxClick());
      } else {
        information.setAttentions(0 + information.getQqClick() + information.getWxClick());
      }
      if (CollUtil.isNotEmpty(imgList)) {
        information.setInfoImgList(imgList);
        information.setImgNum(imgList.size());
      }
    }
    query.setRecords(list);
    return query;
  }

  @Override
  public HyInformationEntity getInformationById(Integer id,Integer userId) {
    /*if (InfoAttentionCache.containsKey(id)) {
      InfoAttentionCache.put(id, (InfoAttentionCache.get(id) + 1));
    } else {

    }*/
    HyInformationEntity information = this.baseMapper.selectById(id);
    //查询用户是否为后台用户，是的话点击量+1
    SysUserEntity sysSubscriber = sysUserService.getBaseMapper().selectById(userId);
    if (ObjectUtil.isNull(sysSubscriber)) {
      // 总点击量+1
      information.setAttention(information.getAttention() + 1);
      // 虚假点击量+1
      information.setAttentions(information.getAttentions() + 1);
    }

    this.baseMapper.updateById(information);
    List<Integer> apkresult = infoSourceServie.getapkById(id);
    // 根据主键关联查询配图置入资讯对象
    List<InfoImgEntity> imglist = infoImgService.getBaseMapper()
      .selectList(new QueryWrapper<InfoImgEntity>().eq("info_id",id));
    // 取所有该资讯的评论
    List<InfoCommentEntity> commentlist = infoCommentService.getInformationCommentforApi(id);
    if (CollUtil.isNotEmpty(commentlist)) {
      // 解析评论对象所有回复
      List<InfoCommentEntity> listhuifu;

      Integer count = commentlist.size();

      for (int i = 0; i < commentlist.size(); i++) {
        listhuifu = infoCommentService.getCommentReplyforApi(commentlist.get(i).getId());
        if (listhuifu != null) {
          commentlist.get(i).setInList(listhuifu);
          for (int j = 0; j < listhuifu.size(); j++) {
            User user = userService.getBaseMapper()
              .selectOne(new QueryWrapper<User>()
                .select("uid","username","rid","email","birthday","head","sex","signature","created")
                .eq("uid",listhuifu.get(j).getUid()));
            if (ObjectUtil.isNotNull(user)) {
              listhuifu.get(j).setUser(user);
            }
          }
        }

        User user = userService.getBaseMapper()
          .selectOne(new QueryWrapper<User>()
            .select("uid","username","rid","email","birthday","head","sex","signature","created")
            .eq("uid",commentlist.get(i).getUid()));
        if (user != null) {
          commentlist.get(i).setUser(user);
        } else {
          infoCommentService.removeById(commentlist.get(i).getId());
        }

      }

      information.setCommentCount(count);
    }
    information.setApkList(apkresult);
    information.setImgList(imglist);
    information.setCommentList(commentlist);
    // 设置总分享次数 = wx分享次数 + qq分享次数
    int sumsharenum = information.getWxShareNum() + information.getQqShareNum();
    information.setSumShareNum(sumsharenum);
    // 设置总点击次数 = 客户端点击次数 + qq渠道分享后点击次数 + 微信渠道分享后点击次数
    information.setAttentions(information.getWxClick() + information.getQqClick() + information.getAttention());
    return information;
  }

  @Override
  public Page getallRecommendInformation(QueryExt query) {
    Map map = new HashMap(16);
    map.putAll(query.getCondition());
    List<HyInformationEntity> result =this.baseMapper.getallRecommendInformation(query,map);
    query.setRecords(result);
    return query;
  }

  @Override
  public Integer put(HyInformationEntity information) {
    // 资讯上传的时候发布状态为0未发布
    information.setState(0);
    information.setAttention(0);
    information.setAttentions(1);
    information.setUpdateTime(new Date());
    information.setCreateTime(new Date());
    this.baseMapper.insert(information);
    return information.getId();
  }

  @Override
  public Integer publishInformation(Integer id) {
    // 发布状态0未发布 1发布2下架
    HyInformationEntity channel = new HyInformationEntity();
    channel.setId(id);
    channel.setState(1);
    channel.setPublishTime(new Date());
    // 审核状态一上线就置为审核通过
    channel.setApprovalStatus(FrogConstant.InformationStatus.APPROVALPASS.getValue());
    channel.setApprovalTime(new Date());
    return this.baseMapper.updateById(channel);
  }

  @Override
  public Integer downInformation(HyInformationEntity channel) {
// 发布状态0未发布 1发布2下架
    channel.setState(2);
    // 审核状态一上线就置为审核通过
    channel.setApprovalStatus(FrogConstant.InformationStatus.APPROVALOFFLINE.getValue());
    channel.setApprovalTime(new Date());
    return this.baseMapper.updateById(channel);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Integer editInformation(HyInformationEntity information) {
    List<InfoImgEntity> list = information.getImgList();
    if (list != null) {
      infoImgDao.updates(list);
    }
    // 设置当前更新时间
    information.setUpdateTime(new Date());
    return this.baseMapper.updateById(information);
  }

  @Override
  public Page getallInformation(QueryExt queryExt) {
    Map map = new HashMap(16);
    map.putAll(queryExt.getCondition());
    List<HyInformationEntity> result =this.baseMapper.getallInformation(queryExt,map);
    for (HyInformationEntity information : result) {
      // 统计出每条资讯下的评论总计
      int ccount = infoCommentService.getBaseMapper()
        .selectCount(new QueryWrapper<InfoCommentEntity>().eq("info_id",information.getId()));
      information.setCountComment(ccount);
      // 统计出总点赞数
      int lcount = infoLikesService.getBaseMapper()
        .selectCount(new QueryWrapper<InfoLikes>().eq("info_id",information.getId()));
      information.setSupport(lcount);
      int sumclick = information.getWxClick() + information.getQqClick() + information.getAttention();
      information.setSumClick(sumclick);
      int sumsharenum = information.getWxShareNum() + information.getQqShareNum();
      information.setSumShareNum(sumsharenum);
    }
    queryExt.setRecords(result);
    return queryExt;
  }

  @Override
  public List<HyInformationEntity> judgeInfoById(Integer id) {
    return this.baseMapper.judgeInfoById(id);
  }
}
